// 这份代码专门处理逻辑层的操作
const importDao = require("../dao/importDao");
const studentDao = require("../dao/studentDao");
const userDao = require("../dao/userDao");
const harmDao = require("../dao/harmDao");
const classesDao = require("../dao/classesDao");

const powerService = require("./powerService");

const importService = {
    /*
     * 导入学生基本信息
     */
    async importStudentsInfo(uid, userType, data) {
        // 判断是否拥有导入学生基本信息的权限
        let result;
        try {
            result = await powerService.checkPowerByUid(uid, "导入学生信息");
            if (result == false) {
                return { success: false, msg: "权限不足，无法操作" };
            }
        } catch (err) {
            return { success: false, msg: "操作过程中出错" };
        }

        try {
            // 获取所有学生的学号
            let cardIdList = await studentDao.getAllCardIdList();
            cardIdList = cardIdList.map((item) => item.id);

            // 将数据分为新增和更新两类
            let newStudents = [];
            let updateStudents = [];

            // 检测学号是否存在重复
            for (let i = 0; i < data.length; i++) {
                let cardId = String(data[i]["学号"]);
                if (cardIdList.includes(cardId)) {
                    updateStudents.push(data[i]);
                } else {
                    newStudents.push(data[i]);
                }
            }

            // 获取所有班级的名称
            let classList = await classesDao.getAllClassNameList();
            classList = classList.map((item) => item.n);

            // 检测班级是否存在
            for (let i = 0; i < data.length; i++) {
                let className = String(data[i]["班级"]);
                if (!classList.includes(className)) {
                    return {
                        success: false,
                        msg: "导入表格中第" + (i + 1) + "行，" + className + " 此班级不存在，导入失败",
                    };
                }
            }

            // 执行导入和更新操作
            result = await importDao.importStudentsInfo(newStudents, updateStudents);
            return {
                success: true,
                msg: `导入成功：${newStudents.length}条新增，${updateStudents.length}条更新`
            };
        } catch (error) {
            return { success: false, msg: "操作数据库时出错，导入失败" };
        }
    },
    /*
     * 导入普查访谈记录
     */
    async importCensusInterviewRecord(uid, userType, data) {
        // 判断是否拥有导入学生基本信息的权限
        let result;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid, "导入普查访谈记录");
            if (result == false) {
                return { success: false, msg: "权限不足，无法操作" };
            }
        } catch (err) {
            return { success: false, msg: "操作过程中出错" };
        }
        // 检查数据的格式是否正确
        try {
            await (async function () {
                // 获取所有学生的学号
                let cardIdList = await studentDao.getAllCardIdList();
                cardIdList = cardIdList.map((item) => item.id);
                // 检测学号是否存在
                for (let i = 0; i < data.length; i++) {
                    let cardId = String(data[i]["学号"]);
                    if (!cardIdList.includes(cardId)) {
                        return {
                            success: false,
                            msg:
                                "导入表格中第" +
                                (i + 1) +
                                "行，" +
                                cardId +
                                "学号不存在，导入失败",
                        };
                    }
                }
            })();
            await (async function () {
                // 获取所有咨询师的姓名
                let counselorsList = await userDao.getAllCounselorsName();
                counselorsList = counselorsList.map((item) => item.name);
                // 检测咨询师是否存在
                for (let i = 0; i < data.length; i++) {
                    let counselor = String(data[i]["访谈人"]);
                    if (!counselorsList.includes(counselor)) {
                        return {
                            success: false,
                            msg:
                                "导入表格中第" +
                                (i + 1) +
                                "行，" +
                                counselor +
                                "该访谈人不存在，导入失败",
                        };
                    }
                }
            })();
            await (async function () {
                // 获取所有预警级别的名称
                let warningLevelList = await harmDao.getAllWarningLevels();
                warningLevelList = warningLevelList.map((item) => item.name);
                // 检测预警级别是否存在
                for (let i = 0; i < data.length; i++) {
                    let warningLevel = String(data[i]["预警级别"]);
                    if (!warningLevelList.includes(warningLevel)) {
                        return {
                            success: false,
                            msg:
                                "导入表格中第" +
                                (i + 1) +
                                "行，" +
                                warningLevel +
                                "这个预警级别不存在，导入失败",
                        };
                    }
                }
            })();
            await (async function () {
                // 获取所有中心意见的名称
                let centerOpinionList = await harmDao.getAllCenterOpinions();
                centerOpinionList = centerOpinionList.map((item) => item.name);
                // 检测中心意见是否存在
                for (let i = 0; i < data.length; i++) {
                    let centerOpinion = String(data[i]["中心意见"]);
                    if (!centerOpinionList.includes(centerOpinion)) {
                        return {
                            success: false,
                            msg:
                                "导入表格中第" +
                                (i + 1) +
                                "行，" +
                                centerOpinion +
                                "这个中心意见不存在，导入失败",
                        };
                    }
                }
            })();
        } catch (err) {
            return { success: false, msg: "操作数据库时出错，导入失败" };
        }
        // 真正的执行逻辑
        try {
            result = await importDao.importCensusInterviewRecord(data);
            result = { success: true, msg: "导入成功" };
        } catch (error) {
            result = { success: false, msg: "操作数据库时出错，导入失败" };
        }
        return result;
    },
    /*
     * 导入测评记录
     */
    async importAssessRecords(uid, userType, data) {
        // 判断是否拥有导入学生基本信息的权限
        let result;
        // // 用户权限认证
        // try {
        //     result = await powerService.checkPowerByUid(uid, '导入普查访谈记录');
        //     if (result == false) {
        //         return {success: false, msg: "权限不足，无法操作"};
        //     }
        // } catch (err) {
        //     return {success: false, msg: "操作过程中出错"};
        // }
        // 检查数据的格式是否正确
        try {
            await (async function () {
                // 获取所有学生的学号
                let cardIdList = await studentDao.getAllCardIdList();
                cardIdList = cardIdList.map((item) => item.id);
                // 检测学号是否存在
                for (let i = 0; i < data.length; i++) {
                    let cardId = String(data[i]["学号"]);
                    if (!cardIdList.includes(cardId)) {
                        return {
                            success: false,
                            msg:
                                "导入表格中第" +
                                (i + 1) +
                                "行，" +
                                cardId +
                                "学号不存在，导入失败",
                        };
                    }
                }
            })();
        } catch (err) {
            return { success: false, msg: "操作数据库时出错，导入失败" };
        }
        // 真正的执行逻辑
        try {
            result = await importDao.importAssessRecords(data);
            result = { success: true, msg: "导入成功", result };
        } catch (error) {
            result = { success: false, msg: "操作数据库时出错，导入失败" };
        }
        return result;
    },
};

module.exports = importService;
